package com.example.easybuy.service.impl;

import com.antherd.smcrypto.sm3.Sm3;
import com.example.easybuy.entity.User;
import com.example.easybuy.exception.NameAndPasswordException;
import com.example.easybuy.mappers.UserMapper;
import com.example.easybuy.service.LoginService;
import com.example.easybuy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.PushbackReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    private UserMapper userMapper;
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public LoginServiceImpl(UserMapper userMapper,StringRedisTemplate redisTemplate){
        this.userMapper= userMapper;
        this.stringRedisTemplate=redisTemplate;
    }

    @Override
    public Map<String, Object> login(String loginName, String password) {
        User user=userMapper.findUser(loginName);
        String sign= Sm3.sm3(password);
        if (user==null||!sign.equals(user.getPassword())){
            throw new NameAndPasswordException();
        }
        String jwt= JwtUtil.createToken(user.getLoginName());
        stringRedisTemplate.opsForValue().set(user.getLoginName(),jwt,60, TimeUnit.MINUTES);
        Map<String,Object> map=new HashMap<>();
        map.put("jwt",jwt);
        map.put("type",user.getType());
        map.put("loginName",user.getLoginName());
        return map;
    }
}